<?php
namespace common\models;

use Yii;
use yii\log\Logger;

use common\tools\WXmlResponseFormatter as WXRF;
use common\tools\YWeChatPrint as WPrint;

use common\wechat\libs\EventFactory;
use common\wechat\libs\ImageFactory;
use common\wechat\libs\TextFactory;
/**
 * Description of WeiChat
 *
 * @author weiwangw
 */
class WeChat {
    
    private $_post;
    private $_returnData;
    
    private $_FromUsername;  
    private $_ToUsername;//接收人  
    private $_MsgType;//消息类型 
    private $_CreateTime; //实践类型
    private $_MsgId;//消息id  
    private $_time;//当前时间做为回复时间  
    
    private function __construct() {
        $this->init();
    }
    
    public static function getinstance(){      
        return new self();
    }
    /**
     * 初始化，加载微信消息参数
     * @return \common\models\WeiChat
     */
    private function init(){       
        $this->_post = simplexml_load_string(Yii::$app->request->getRawBody(), 'SimpleXMLElement', LIBXML_NOCDATA);
        $this->_returnData = [];
        
        if(empty($this->_post)){
            Yii::getLogger()->log('微信消息加载失败', Logger::LEVEL_ERROR);    
            return $this;
        }       
        $this->_FromUsername = $this->_post->FromUserName;//发送人  
        $this->_ToUsername   = $this->_post->ToUserName;//接收人  
        $this->_MsgType      = $this->_post->MsgType;//消息类型 
        $this->_MsgId        = $this->_post->MsgId; //消息id 
        $this->_CreateTime   = $this->_post->CreateTime; //消息时间
        $this->_time         = time();//当前时间做为回复时间   
        $this->weixinLogin($this->_FromUsername);//登录
        $worker = $this->easyBoot();
        $this->_returnData = $worker->startFactory()->createReMsg(); 
    }
    /***
     * 处理微信消息主方法
     */
    public function easyBoot()
    {
        if(empty($this->_MsgType)){
            return false;
        }
        
        switch ($this->_MsgType){
            case "event": 
                return new EventFactory($this->_post);
                break; 
            case "image":   
                return new ImageFactory($this->_post);
                break; 
            case "location":   
                 
            case "link":     
               
            case "voice":    
               
            case "text": 
            default:
                return new TextFactory($this->_post);
                break;   
        }                                                      
    }
    public function getPost(){
        return $this->_post;
    }
    public function responseMsg () {       
        Yii::getLogger()->log($this->_returnData, Logger::LEVEL_INFO);    
        return \Yii::createObject([ 
            'class' => 'yii\web\Response', 
            'format' => \yii\web\Response::FORMAT_XML, 
            'formatters' => [ 
                \yii\web\Response::FORMAT_XML => [ 
                    'class' => 'common\tools\WXmlResponseFormatter', 
                ], 
            ], 
            'data'=>$this->_returnData
        ]); 
    }
    private function weixinLogin($openid){
        $user = User::findByOpenid($openid);
        if ($user && Yii::$app->user->login($user, 3600 * 24 * 30)) {
//            return $this->goBack(Url::to(['/album']));
        } else {
            $flag = User::addUserByOpenid($openid);
            if($flag){
                $user = User::findByOpenid($openid);
                $user && Yii::$app->user->login($user, 3600 * 24 * 30);
//                if($user && Yii::$app->user->login($user, 3600 * 24 * 30))
//                    return $this->goBack(Url::to(['/album']));
            }
//            $model = new LoginForm();
//            return $this->render('login', [
//                'model' => $model,
//                "flag" =>true
//            ]);          
        }              
    }
    
}
